package com.shouyun.modules.security.controller;

import com.alibaba.fastjson.JSONObject;
import com.shouyun.common.constant.Constant;
import com.shouyun.common.exception.ErrorCode;
import com.shouyun.common.exception.ShouYunException;
import com.shouyun.common.utils.DataUtils;
import com.shouyun.common.utils.Result;
import com.shouyun.common.validator.AssertUtils;
import com.shouyun.common.validator.ValidatorUtils;
import com.shouyun.modules.security.dto.LoginDTO;
import com.shouyun.modules.security.service.CaptchaService;
import com.shouyun.modules.security.service.SysUserTokenService;
import com.shouyun.modules.security.user.SecurityUser;
import com.shouyun.modules.security.user.UserDetail;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录
 *
 * @author Sunshouguo sunshouguo_java@163.com
 */
@RestController
public class LoginController {
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private CaptchaService captchaService;

    /**
     * 验证码
     *
     * @param response
     * @param uuid
     * @throws IOException
     */
    @GetMapping("captcha")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        //uuid不能为空
        AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);

        //生成验证码
        captchaService.create(response, uuid);
    }

    /**
     * 登录
     *
     * @param request
     * @param login
     * @return
     */
    @PostMapping("login")
    public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
        //效验数据
        ValidatorUtils.validateEntity(login);

        //验证码是否正确
        if (login.getIsCaptcha()) {
            boolean flag = captchaService.validate(login.getUuid(), login.getCaptcha());
            if (!flag) {
                return new Result().error(ErrorCode.CAPTCHA_ERROR);
            }
        }

        JSONObject user = DataUtils.getData(DataUtils.USER, login.getUsername());
        //用户不存在
        if (user == null) {
            throw new ShouYunException(ErrorCode.ACCOUNT_NOT_EXIST);
        }

        //密码错误
//		if(!PasswordUtils.matches(login.getPassword(), user.getPassword())){
        if (!login.getPassword().equals(user.getString("password"))) {
            throw new ShouYunException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //获取请求token
        String token = getRequestToken(request);
        return sysUserTokenService.createToken(token, user);
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("logout")
    public Result logout(HttpServletRequest request) {
        //获取请求token
        String token = getRequestToken(request);
        UserDetail user = SecurityUser.getUser();

        //退出
        sysUserTokenService.logout(token);

        return new Result();
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        //从header中获取token
        String token = httpRequest.getHeader(Constant.TOKEN_HEADER);

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter(Constant.TOKEN_HEADER);
        }

        return token;
    }
}